package com.example.demo.controller;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.demo.config.AlipayTemplate;
import com.example.demo.entity.Buy;
import com.example.demo.entity.PayVo;
import com.example.demo.entity.Price;
import com.example.demo.entity.article;
import com.example.demo.mapper.articleMapper;
import com.example.demo.model.result;
import com.example.demo.services.BuyService;
import com.example.demo.services.OrderService;
import com.example.demo.services.articleService;
import com.example.demo.utils.SnowflakeIdWorker;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class articleController {

    @Autowired
    private articleService articleService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayTemplate aliPayTemplate;

    @Autowired
    private BuyService buyService;

    private Logger logger= LoggerFactory.getLogger(getClass());


    @GetMapping("/all")
    public result selectall(){
        logger.info("用户正在查询所有文章");
        return result.success(articleService.selectall());
    }


    /**
     * 用户添加文章信息
     * @param name 文章类别分类
     * @param title 文章主题
     * @param content 文章内容
     * @param userName 作者姓名
     * @param userId 作者编号
     * @param dateTime 创建时间
     * @param img div背景图片 输入的字符串应该为图片的命名 前端会自动补充地址
     * @return
     */
    @PostMapping("/add")
    public result addArticle(String name, String title, String content, String userName, String userId, LocalDateTime dateTime, String img){
        logger.info("用户正在添加文章数据");
        return result.success(articleService.addArticle(name, title, content, userName, userId, dateTime, img));
    }


    @PutMapping("/update")
    public result updateArticle(String content,Integer id){
        logger.info("用户修改文章内容");
        return result.success(articleService.updateArticle(content, id));

    }


    @GetMapping("/get")
    public result getId(Integer id){
        return result.success(articleService.selectId(id));
    }


    /**
     * 根据 name 分类 文章 类型
     */
    @GetMapping("/selectname")
    public result selectname(@Param("name") String name,@Param("num")Integer num){
        logger.info("用户正在查看{}类型的文章",name);
        return result.success(articleService.selectname(name,num));
    }

    /**
     * 查看指定文章 contentId必须和param一致不然无法获取值
     */
    @GetMapping("/selectId")
    public result selectId(@Param("contentId")Integer contentId){
        logger.info("用户正在查看{}文章",contentId);
        return result.success(articleService.selectId(contentId));
    }

    @GetMapping(value = "/payOrder",produces = "text/html")
    @ResponseBody
    public String payOrder(@RequestParam("orderSn")String orderSn, @Param("id")Integer id,@Param("userId")String userId,@Param("userName")String name,HttpSession session,@Param("name")String artiName) throws AlipayApiException, UnsupportedEncodingException {

        String noStr= SnowflakeIdWorker.generateId()+"";
        logger.info("订单id:{}",noStr);
        //订单写入session学生id 对应商品id

//        Buy buy=new Buy();
//        buy.setUserId(userId);
//        buy.setArticleId(id);
//        buy.setUserName(name);
        //拼接 学号和商品号
        String pinjie=userId+","+String.valueOf(id);
        session.setAttribute("userId",pinjie);
        PayVo payVo=orderService.getPay(noStr,id,userId,name);

        return aliPayTemplate.pay(payVo,session);
    }

    @GetMapping(value = "/testPay")
    public void testpay() throws AlipayApiException {
        aliPayTemplate.test();
    }



    @GetMapping("/success")
    public String success(){
        return "支付成功";
    }


    @PostMapping("/payResult")
    public String alipayNotify(HttpServletRequest request, HttpSession session)throws Exception{
        Map<String, String> map = new HashMap<>();
        logger.info("支付成功返回{}",request.getParameterMap());
        logger.info("session为{}",session);
        Map<String, String[]> requestParams = request.getParameterMap();
        if(requestParams.isEmpty()) {
            return "failure";
        }
        Object te= session.getAttribute("2021110800001600");

        // 将 Map<String,String[]> 转为 Map<String,String>
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            Object object= requestParams.get("subject");
            Object object1=requestParams.get("body");
            Object object2=requestParams.get("total_amount");
            Object userId=requestParams.get("passback_params");
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        // 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(map, aliPayTemplate.getAlipayPublicKey(), aliPayTemplate.getCharset(),
                aliPayTemplate.getSignType());
        // 验签通过
        if (signVerified) {
            //支付成功后进行操作
            String cheshi=new String(request.getParameter("passback_params").getBytes("ISO-8859-1"),"UTF-8");
            String userId= URLDecoder.decode(cheshi,"UTF-8");
            logger.info("用户{}购买成功",userId);
            System.out.println(userId);
            String body=userId+","+map.get("body")+","+map.get("invoice_amount");
            System.out.println(body);
            String[] st=body.split(",");
//            for (int i=0;i<st.length;i++){
//                System.out.println(st[i]);
//            }
            Buy buy=new Buy();
            buy.setUserId(st[0]);
            buy.setArticleId(Integer.valueOf(st[1]));
            buy.setArticleTitle(st[2]);
            buy.setPrice(Double.valueOf(st[3]).intValue());

            buyService.insertBuy(buy);
        }
        return "failure";
    }



}
